﻿using System.IO;
using Ionic.Zip;

namespace MSDNWebcast.Utils
{
    /// <summary>
    /// 解压帮助
    /// </summary>
    public class ZipUtil
    {
        /// <summary>
        /// 解压单个文件
        /// </summary>
        /// <param name="zipPathAndFile"></param>
        /// <param name="fileName"></param>
        /// <param name="deleteZipFile"></param>
        public static void UnZipFile(string zipPathAndFile, string fileName, bool deleteZipFile)
        {
            using (ZipFile zip = ZipFile.Read(zipPathAndFile))
            {
                if (!Directory.Exists(Path.GetDirectoryName(fileName)))
                    Directory.CreateDirectory(Path.GetDirectoryName(fileName));

                if (zip.Count < 1) return;
                using (FileStream stream = File.Create(fileName))
                {
                    zip[0].Extract(stream);
                    stream.Close();
                }
            }

            if (deleteZipFile)
                File.Delete(zipPathAndFile);
        }

        /// <summary>
        /// 解压文件
        /// </summary>
        /// <param name="zipPathAndFile"></param>
        /// <param name="outputFolder"></param>
        /// <param name="deleteZipFile"></param>
        public static void UnZipFiles(string zipPathAndFile, string outputFolder, bool deleteZipFile)
        {
            using (ZipFile zip = ZipFile.Read(zipPathAndFile))
            {
                if (!Directory.Exists(outputFolder))
                    Directory.CreateDirectory(outputFolder);

                foreach (var zipFile in zip)
                {
                    zipFile.Extract(outputFolder, ExtractExistingFileAction.OverwriteSilently);
                }
            }

            if (deleteZipFile)
                File.Delete(zipPathAndFile);
        }
    }
}
